<?php
// +---------------------------------------------------------------------+
// | OneBase    | [ WE CAN DO IT JUST THINK ]                            |
// +---------------------------------------------------------------------+
// | Licensed   | http://www.apache.org/licenses/LICENSE-2.0 )           |
// +---------------------------------------------------------------------+
// | Author     | Bigotry <3162875@qq.com>                               |
// +---------------------------------------------------------------------+
// | Repository | https://gitee.com/Bigotry/OneBase                      |
// +---------------------------------------------------------------------+

/**
 * 应用公共（函数）文件
 */

use think\Db;
use think\Response;
use think\exception\HttpResponseException;


// +---------------------------------------------------------------------+
// | 系统相关函数
// +---------------------------------------------------------------------+

/**
 * 检测用户是否登录
 * @return integer 0-未登录，大于0-当前登录用户ID
 */
function is_login()
{

    $member = session('member_auth');

    if (empty($member)) {

        return DATA_DISABLE;
    } else {

        return session('member_auth_sign') == data_auth_sign($member) ? $member['member_id'] : DATA_DISABLE;
    }
}

/****
 * @return bool  检测当前是否https
 *
 */
function is_https() {
    if ( !empty($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off') {
        return true;
    } elseif ( isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https' ) {
        return true;
    } elseif ( !empty($_SERVER['HTTP_FRONT_END_HTTPS']) && strtolower($_SERVER['HTTP_FRONT_END_HTTPS']) !== 'off') {
        return true;
    }
    return false;
}

function baidu_translate($str,$to='en')
{

    if(!$to){
        return $str;
    }
    switch ($to){
        case 'zh-cn':
            $to='cht';
            break;
        case 'en-us':
            $to='en';
            break;

    }

    $data['q'] = $str;
    $data['from'] = 'zh';
    $data['to'] = $to;
    $data['appid'] = '20190326000281391';
    $data['salt'] = create_rand_number(1);
    $data['sign'] = md5($data['appid'] . $data['q'] . $data['salt'] . 'kNQCFLJ9ChytdVyMjoAE');

    $url = 'http://api.fanyi.baidu.com/api/trans/vip/translate';
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3000);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);  // 从证书中检查SSL加密算法是否存在
    $handles = curl_exec($ch);
    $error = null;
    if ($handles === false) {
        $error = curl_error($ch);
    }
    if (!empty($error) || empty($handles)) {
        \Think\Log::record('获取失败，' . $error);
        curl_close($ch);
        return $str;
    }
    $result = json_decode($handles, true);
    if (empty($result)) {
        return $str;
    }
    if (!empty($result['error_code'])) {
        return $str;
    }
    $list = $result['trans_result'];
    foreach ($list as $key => $bean) {
        $str = str_replace(urldecode($bean['src']), $bean['dst'], $str);
    }
    return $str;
}


/**
 * 获取 IP  地理位置
 * 淘宝IP接口
 * @Return: array
 */
function getCity($ip = '')
{

    $url = "http://ip.taobao.com/service/getIpInfo.php?ip=" . $ip;
    $ip = json_decode(file_get_contents($url));
    if ((string)$ip->code == '1') {
        return false;
    }
    $data = (array)$ip->data;
    return $data;

}

    function exchange_time($time1){
    $time=time();
    $minute=floor(($time-$time1)/60);
    $hour=floor($minute/60);
    $day=floor($hour/24);
    $month=floor($day/30);
    if(floor(($time-$time1))<60){
        $new_time=floor(($time-$time1)).lang('秒前');
    }elseif($minute<60){
        $new_time=$minute.lang('分钟前');

    }elseif($hour<24){
        $new_time=$hour.lang('小时前');

    }elseif($day<30){
        $new_time=$day.lang('天前');
    }else{

        $new_time=$month.lang('月前');
    }

    return $new_time;

}

/**
 * 获得随机字符串
 * @param $len
 * @param $special
 * @return string       返回随机字符串
 */
function getRandomStr($len, $special=true){
    $chars = array(
        "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
        "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
        "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",
        "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
        "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2",
        "3", "4", "5", "6", "7", "8", "9"
    );

    if($special){
        $chars = array_merge($chars, array(
            "!", "@", "#", "$", "?", "|", "{", "/", ":", ";",  "%", "^", "&", "*", "(", ")", "-", "_", "[", "]",
            "}", "<", ">", "~", "+", "=", ",", "."
        ));
    }

    $charsLen = count($chars) - 1;
    shuffle($chars);                            //打乱数组顺序
    $str = '';
    for($i=0; $i<$len; $i++){
        $str .= $chars[mt_rand(0, $charsLen)];    //随机取出一位
    }
    return $str;
}

//列表转换成树
function buildListToTree($idName,$allList,$parentId=0){
    $tree=array();
    //一级
    foreach ($allList as $bean){
        if($bean['parent_id']==$parentId){
            $childrenList=findChildren($idName,$bean,$allList);
            if(count($childrenList)!=0){
                $bean['children']=$childrenList;
            }
            $tree[]=$bean;
        }
    }
    return $tree;
}
function findChildren($idName,$rootBean,$allList=array())
{
    $childrenList = array();
    foreach ($allList as $bean) {
        if ($bean['parent_id'] == 0 || $bean['parent_id'] == '') {
            continue;
        }

        if ($rootBean[$idName] == $bean['parent_id']) {
            $childrenList[] = $bean;
        }
    }
    if (count($childrenList) != 0) {
        foreach ($childrenList as $key => $bean) {
            $items = findChildren($idName, $bean, $allList);
            if (count($items) != 0) {
                $childrenList[$key]['children'][] = $items;
            }
        }
    }
    return $childrenList;
}

//列表转换成树
function buildSortTreeList($fieldId,$fieldName,$allList,$parentId='0',$space=''){
    $tree=array();
    foreach ($allList as $bean){
        if($bean['parent_id']==$parentId){
            $bean[$fieldName]=$space.$bean[$fieldName];
            $tree[]=$bean;
            $childList=buildSortTreeList($fieldId,$fieldName,$allList,$bean[$fieldId],$space.'------');
            if(!empty($childList)){
                $tree=array_merge($tree,$childList);
            }
        }
    }
    return $tree;
}
//树转换成列表--系统配置修改用到
function buildTreeToList($tree){
    $allList=array();
    //一级
    foreach ($tree as $bean){
        if(isset($bean['children'])&&count($bean['children'])!=0){
            //存在子项
            $allList=array_merge($allList,buildTreeToList($bean['children']));
        }
        if(isset($bean['children'])){
            unset($bean['children']);
        }
        $allList[]=$bean;
    }
    return $allList;
}//手机验证
function match_mobile($mobile)
{
    return preg_match("/^1[345678]\d{9}$/", $mobile);
}

/***
 * 隐藏中间四位
 * @param $str
 * @return mixed
 */
function yc_phone($str)
{

    $resstr = substr_replace($str, '****', 3, 4);
    return $resstr;
}

/**
 * 系统非常规MD5加密方法
 * @param  string $str 要加密的字符串
 * @return string
 */
function data_md5($str, $key = 'OneBase')
{

    return '' === $str ? '' : md5(sha1($str) . $key);
}
/**
 * 获取客户端IP地址
 * @param integer $type 返回类型 0 返回IP地址 1 返回IPV4地址数字
 * @return mixed
 */
function get_client_ip($type = 0) {
    $type       =  $type ? 1 : 0;
//    static $ip  =   NULL;
//    if ($ip !== NULL) return $ip[$type];
//    if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
//        $arr    =   explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
//        $pos    =   array_search('unknown',$arr);
//        if(false !== $pos) unset($arr[$pos]);
//        $ip     =   trim($arr[0]);
//    }elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
//        $ip     =   $_SERVER['HTTP_CLIENT_IP'];
//    }elseif (isset($_SERVER['REMOTE_ADDR'])) {
//        $ip     =   $_SERVER['REMOTE_ADDR'];
//    }
    $ip     =   $_SERVER['REMOTE_ADDR'];
    // IP地址合法验证
    $long = sprintf("%u",ip2long($ip));
    $ip   = $long ? array($ip, $long) : array('0.0.0.0', 0);
    return $ip[$type];
}

/**
 * 请求接口返回内容
 * @param  string $url [请求的URL地址]
 * @param  string $params [请求的参数]
 * @param  int $ipost [是否采用POST形式]
 * @return  string
 */
function mycurl($url, $params = false, $ispost = 0,$headers=[]) {
    $httpInfo = array();
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.172 Safari/537.22');
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT,30);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_ACCEPT_ENCODING, "gzip,deflate");
    if (!empty($headers)) {
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
//        curl_setopt($ch, CURLOPT_HEADER, 0);//返回response头部信息
    }
    if ($ispost) {
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
        curl_setopt($ch, CURLOPT_URL, $url);
    } else {
        if ($params) {
            curl_setopt($ch, CURLOPT_URL, $url . '?' . $params);
        } else {
            curl_setopt($ch, CURLOPT_URL, $url);
        }
    }
    $response = curl_exec($ch);

    if ($response === FALSE) {
        return false;
    }
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $httpInfo = array_merge($httpInfo, curl_getinfo($ch));
    curl_close($ch);
    return $response;
}

/**
 * @param $api_key
 * @param $api_secret
 * @param $data
 * @return false|string
 */
function api_format_data($api_key,$api_secret,$data){
    $timestamp = date("Y/m/d H:i:s");
    $sign = md5("apikey".$api_key."secretkey".$api_secret."timestamp".$timestamp);

    $format_data['ApiKey'] = $api_key;
    $format_data['Sign'] = $sign;
    $format_data['Timestamp'] = $timestamp;
    $format_data['Data'] = $data;
    $format_data = json_encode($format_data);
    return $format_data;
}

/**
 * @param $appkey
 * @param $tel_check_url
 * @param $mobile
 * @param $pervalue
 * @return bool
 */
function telcheck($appkey,$tel_check_url,$mobile,$pervalue){
    $params = 'key='.$appkey.'&phoneno='.$mobile.'&cardnum='.$pervalue;
    $content = juhecurl($tel_check_url,$params);

    $result = returnArray($content);

    if($result['error_code'] == '0'){
        return true;
    }else{
        return false;
    }
}

/**
 * @param $appkey
 * @param $tel_query_url
 * @param $mobile
 * @param $pervalue
 * @return mixed
 */
function telquery($appkey,$tel_query_url,$mobile,$pervalue){
    $params = 'key='.$appkey.'&phoneno='.$mobile.'&cardnum='.$pervalue;
    $content = juhecurl($tel_query_url,$params);
    return returnArray($content);
}

/**
 * @param $open_id
 * @param $app_key
 * @param $submit_url
 * @param $mobile
 * @param $pervalue
 * @param $orderid
 * @return mixed
 */
function telcz($open_id,$app_key,$submit_url,$mobile,$pervalue,$orderid){
    $sign = md5($open_id.$app_key.$mobile.$pervalue.$orderid);//校验值计算
    $params = array(
        'key' => $app_key,
        'phoneno'   => $mobile,
        'cardnum'   => $pervalue,
        'orderid'   => $orderid,
        'sign' => $sign
    );
    $content = juhecurl($submit_url,$params,1);
    return returnArray($content);
}

/**
 * @param $orderid
 * @return mixed
 */
function sta($app_key,$orderid){
    $params = 'key='.$app_key.'&orderid='.$orderid;
    $content = juhecurl($this->staUrl,$params);
    return returnArray($content);
}

/**
 * @param $content
 * @return mixed
 */
function returnArray($content){
    return json_decode($content,true);
}

/**
 * @param $url
 * @param bool $params
 * @param int $ispost
 * @return bool|string
 */
function juhecurl($url,$params=false,$ispost=0){
    $httpInfo = array();
    $ch = curl_init();

    curl_setopt( $ch, CURLOPT_HTTP_VERSION , CURL_HTTP_VERSION_1_1 );
    curl_setopt( $ch, CURLOPT_USERAGENT , 'JuheData' );
    curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT , 60 );
    curl_setopt( $ch, CURLOPT_TIMEOUT , 60);
    curl_setopt( $ch, CURLOPT_RETURNTRANSFER , true );
    if( $ispost )
    {
        curl_setopt( $ch , CURLOPT_POST , true );
        curl_setopt( $ch , CURLOPT_POSTFIELDS , $params );
        curl_setopt( $ch , CURLOPT_URL , $url );
    }
    else
    {
        if($params){
            curl_setopt( $ch , CURLOPT_URL , $url.'?'.$params );
        }else{
            curl_setopt( $ch , CURLOPT_URL , $url);
        }
    }
    $response = curl_exec( $ch );
    if ($response === FALSE) {
        //echo "cURL Error: " . curl_error($ch);
        return false;
    }
    $httpCode = curl_getinfo( $ch , CURLINFO_HTTP_CODE );
    $httpInfo = array_merge( $httpInfo , curl_getinfo( $ch ) );
    curl_close( $ch );
    return $response;
}

/**
 * @param array $params
 * @return bool|string
 */
 function  taxi_asc_sort($params = array())
{
    if (!empty($params)) {
        $p = ksort($params);

        if ($p) {
            $str = '';
            foreach ($params as $k => $val) {
                $str .= $k . '=' . $val . '&';
            }
            $strs = rtrim($str, '&');
            return $strs;
        }
    }
    return false;
}

/**
 * https请求接口返回内容
 * @param  string $url [请求的URL地址]
 * @param  string $params [请求的参数]
 * @param  int $ipost [是否采用POST形式]
 * @return  string
 */
function https_curl($url,$params=false,$ispost=0){

    $httpInfo = array();
    $ch = curl_init(); // 启动一个CURL会话
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); // 从证书中检查SSL加密算法是否存在
    curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
    curl_setopt($ch, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
    curl_setopt($ch, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
    curl_setopt($ch, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
    if ($ispost) {
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
        curl_setopt($ch, CURLOPT_URL, $url);
    } else {
        if ($params) {
            curl_setopt($ch, CURLOPT_URL, $url . '?' . $params);
        } else {
            curl_setopt($ch, CURLOPT_URL, $url);
        }
    }
    $response = curl_exec($ch);
    if ($response === FALSE) {
        return false;
    }
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $httpInfo = array_merge($httpInfo, curl_getinfo($ch));
    curl_close($ch);
    return $response;
}

/**
 * 使用上面的函数与系统加密KEY完成字符串加密
 * @param  string $str 要加密的字符串
 * @return string
 */
function data_md5_key($str, $key = '')
{

    if (is_array($str)) {

        ksort($str);

        $data = http_build_query($str);

    } else {

        $data = (string) $str;
    }

    return empty($key) ? data_md5($data, SYS_ENCRYPT_KEY) : data_md5($data, $key);
}
function replaceSpecialChar($strParam){
    $regex = "/\/|\~|\!|\@|\#|\\$|\%|\^|\&|\*|\(|\)|\（|\）|\_|\+|\{|\}|\:|\<|\>|\?|\[|\]|\,|\.|\/|\;|\'|\`|\-|\=|\\\|\||\s+/";
    if(preg_match($regex,$strParam)){
        return true;
    }
    return false;

}

/**
 * 数据签名认证
 * @param  array  $data 被认证的数据
 * @return string       签名
 */
function data_auth_sign($data)
{

    // 数据类型检测
    if (!is_array($data)) {

        $data = (array)$data;
    }

    // 排序
    ksort($data);

    // url编码并生成query字符串
    $code = http_build_query($data);

    // 生成签名
    $sign = sha1($code);

    return $sign;
}

/**
 * 检测当前用户是否为管理员
 * @return boolean true-管理员，false-非管理员
 */
function is_administrator($member_id = null)
{

    $return_id = is_null($member_id) ? is_login() : $member_id;

    return $return_id && (intval($return_id) === SYS_ADMINISTRATOR_ID);
}

/**
 * 获取单例对象
 */
function get_sington_object($object_name = '', $class = null)
{

    $request = request();

    $request->__isset($object_name) ?: $request->bind($object_name, new $class());

    return $request->__get($object_name);
}

/**
 * 获取插件类的类名
 * @param strng $name 插件名
 */
function get_addon_class($name = '')
{

    $lower_name = strtolower($name);

    $class = SYS_ADDON_DIR_NAME. SYS_DS_CONS . $lower_name . SYS_DS_CONS . $name;

    return $class;
}

/**
 * 钩子
 */
function hook($tag = '', $params = [])
{

    \think\Hook::listen($tag, $params);
}

/**
 * 插件显示内容里生成访问插件的url
 * @param string $url url
 * @param array $param 参数
 */
function addons_url($url, $param = array())
{

    $parse_url  =  parse_url($url);
    $addons     =  $parse_url['scheme'];
    $controller =  $parse_url['host'];
    $action     =  $parse_url['path'];

    /* 基础参数 */
    $params_array = array(
        'addon_name'      => $addons,
        'controller_name' => $controller,
        'action_name'     => substr($action, 1),
    );

    $params = array_merge($params_array, $param); //添加额外参数

    return url('addon/execute', $params);
}

/**
 * 插件对象注入
 */
function addon_ioc($this_class, $name, $layer)
{

    !str_prefix($name, $layer) && exception('逻辑与模型层引用需前缀:' . $layer);

    $class_arr = explode(SYS_DS_CONS, get_class($this_class));

    $sr_name = sr($name, $layer);

    $class_logic = SYS_ADDON_DIR_NAME . SYS_DS_CONS . $class_arr[DATA_NORMAL] . SYS_DS_CONS . $layer . SYS_DS_CONS . $sr_name;

    return get_sington_object(SYS_ADDON_DIR_NAME . '_' . $layer . '_' . $sr_name, $class_logic);
}

/**
 * 抛出响应异常
 */
function throw_response_exception($data = [], $type = 'json')
{

    $response = Response::create($data, $type);

    throw new HttpResponseException($response);
}

/**
 * 获取访问token
 */
function get_access_token()
{

    return md5('OneBaseCCIE' . API_KEY);
}

/**
 * 格式化字节大小
 * @param  number $size      字节数
 * @param  string $delimiter 数字和单位分隔符
 * @return string            格式化后的带单位的大小
 */
function format_bytes($size, $delimiter = '')
{

    $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');

    for ($i = 0; $size >= 1024 && $i < 5; $i++) {

        $size /= 1024;
    }

    return round($size, 2) . $delimiter . $units[$i];
}


// +---------------------------------------------------------------------+
// | 数组相关函数
// +---------------------------------------------------------------------+

/**
 * 把返回的数据集转换成Tree
 * @param array $list 要转换的数据集
 * @param string $pid parent标记字段
 * @param string $level level标记字段
 * @return array
 */
function list_to_tree($list, $pk='id', $pid = 'pid', $child = '_child', $root = 0)
{

    // 创建Tree
    $tree = [];

    if (!is_array($list)) {

        return false;
    }

    // 创建基于主键的数组引用
    $refer = [];

    foreach ($list as $key => $data) {

        $refer[$data[$pk]] =& $list[$key];
    }

    foreach ($list as $key => $data) {

        // 判断是否存在parent
        $parentId =  $data[$pid];

        if ($root == $parentId) {

            $tree[] =& $list[$key];

        } else if (isset($refer[$parentId])){

            is_object($refer[$parentId]) && $refer[$parentId] = $refer[$parentId]->toArray();

            $parent =& $refer[$parentId];

            $parent[$child][] =& $list[$key];
        }
    }

    return $tree;
}

/**
 * 获取最大数量
 */

function get_max_number($number){
    $arr=[10000000,1000000,100000,10000,1000,100];
    $max=100;
    foreach ($arr as $k=>$v){
        if($number>$v){
            if($k==0){
                $max=$v;
                break;
            }else{
                $max=$arr[$k-1];
                break;
            }

        }
    }

    return $max;

}

/**
 * 分析数组及枚举类型配置值 格式 a:名称1,b:名称2
 * @return array
 */
function parse_config_attr($string)
{

    $array = preg_split('/[,;\r\n]+/', trim($string, ",;\r\n"));

    if (strpos($string, ':')) {

        $value = [];

        foreach ($array as $val) {

            list($k, $v) = explode(':', $val);

            $value[$k] = $v;
        }

    } else {

        $value = $array;
    }

    return $value;
}

/**
 * 解析数组配置
 */
function parse_config_array($name = '')
{

    return parse_config_attr(config($name));
}

/**
 * 将二维数组数组按某个键提取出来组成新的索引数组
 */
function array_extract($array = [], $key = 'id')
{

    $count = count($array);

    $new_arr = [];

    for($i = 0; $i < $count; $i++) {

        if (!empty($array) && !empty($array[$i][$key])) {

            $new_arr[] = $array[$i][$key];
        }
    }

    return $new_arr;
}

/**
 * 根据某个字段获取关联数组
 */
function array_extract_map($array = [], $key = 'id'){


    $count = count($array);

    $new_arr = [];

    for($i = 0; $i < $count; $i++) {

        $new_arr[$array[$i][$key]] = $array[$i];
    }

    return $new_arr;
}

/**
 * 页面数组提交后格式转换
 */
function transform_array($array)
{

    $new_array = array();
    $key_array = array();

    foreach ($array as $key=>$val) {

        $key_array[] = $key;
    }

    $key_count = count($key_array);

    foreach ($array[$key_array[0]] as $i => $val) {

        $temp_array = array();

        for( $j=0;$j<$key_count;$j++ ){

            $key = $key_array[$j];
            $temp_array[$key] = $array[$key][$i];
        }

        $new_array[] = $temp_array;
    }

    return $new_array;
}

/**
 * 页面数组转换后的数组转json
 */
function transform_array_to_json($array)
{

    return json_encode(transform_array($array));
}

/**
 * 关联数组转索引数组
 */
function relevance_arr_to_index_arr($array)
{

    $new_array = [];

    foreach ($array as $v)
    {

        $temp_array = [];

        foreach ($v as $vv)
        {
            $temp_array[] = $vv;
        }

        $new_array[] = $temp_array;
    }

    return $new_array;
}

/**
 * 数组转换为字符串，主要用于把分隔符调整到第二个参数
 * @param  array  $arr  要连接的数组
 * @param  string $glue 分割符
 * @return string
 */
function arr2str($arr, $glue = ',')
{

    return implode($glue, $arr);
}


// +---------------------------------------------------------------------+
// | 字符串相关函数
// +---------------------------------------------------------------------+

/**
 * 字符串转换为数组，主要用于把分隔符调整到第二个参数
 * @param  string $str  要分割的字符串
 * @param  string $glue 分割符
 * @return array
 */
function str2arr($str, $glue = ',')
{

    return explode($glue, $str);
}

/**
 * 字符串替换
 */
function sr($str = '', $target = '', $content = '')
{

    return str_replace($target, $content, $str);
}

/**
 * 字符串前缀验证
 */
function str_prefix($str, $prefix)
{

    return strpos($str, $prefix) === DATA_DISABLE ? true : false;
}

// +---------------------------------------------------------------------+
// | 文件相关函数
// +---------------------------------------------------------------------+

/**
 * 获取目录下所有文件
 */
function file_list($path = '')
{

    $file = scandir($path);

    foreach ($file as $k => $v) {

        if (is_dir($path . SYS_DS_PROS . $v)) {

            unset($file[$k]);
        }
    }

    return array_values($file);
}

/**
 * 获取目录列表
 */
function get_dir($dir_name)
{

    $dir_array = [];

    if (false != ($handle = opendir($dir_name))) {

        $i = 0;

        while (false !== ($file = readdir($handle))) {

            if ($file != "." && $file != ".."&&!strpos($file,".")) {

                $dir_array[$i] = $file;

                $i++;
            }
        }

        closedir($handle);
    }

    return $dir_array;
}

/**
 * 获取文件根目录
 */
function get_file_root_path()
{

    $root_arr = explode(SYS_DS_PROS, URL_ROOT);

    array_pop($root_arr);

    $root_url = arr2str($root_arr, SYS_DS_PROS);

    return $root_url . SYS_DS_PROS;
}

/**
 * 获取图片url
 */
function get_picture_url($id = 0,$true=true)
{

    $info = Db::name('picture')->where(['id' => $id])->field('path,url')->find();

    if (!empty($info['url'])) {

        return  $info['url'];
    }

    $root_url = get_file_root_path();

    if (!empty($info['path'])) {

        return $true?$root_url . 'upload/picture/'.$info['path']:DMOAIN_URL .'/'. 'upload/picture/'.$info['path'];
    }

    return $true?$root_url . 'static/module/admin/img/onimg.png':DMOAIN_URL  . '/static/module/admin/img/onimg.png';
}

/**
 * curl 抓取内容
 *
 * @param $url
 * @param int $timeout
 *
 * @return bool|mixed
 */
if (!function_exists("get_url_content")) {
    function get_url_content($url, $options = array(), $timeout = 60)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
//    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322)');
//    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; Baiduspider/2.0; +http://www.baidu.com/search/spider.html');
        curl_setopt($ch, CURLOPT_USERAGENT,
            'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/55.0.1180.89 Safari/537.1');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        // extra options?
        if (!empty($options)) {
            curl_setopt_array($ch, $options);
        }
        $data = curl_exec($ch);
        $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        return $data;
    }
}

function create_invite_code() {
    $code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $rand = $code[rand(0,25)]
        .strtoupper(dechex(date('m')))
        .date('d')
        .substr(time(),-5)
        .substr(microtime(),2,5)
        .sprintf('%02d',rand(0,99));
    for(
        $a = md5( $rand, true ),
        $s = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ',
        $d = '',
        $f = 0;
        $f < 8;
        $g = ord( $a[ $f ] ),
        $d .= $s[ ( $g ^ ord( $a[ $f + 8 ] ) ) - $g & 0x1F ],
        $f++
    );
    return $d;
}

/**
 * 获取钱包列表
 */
function get_wallet_list()
{

    $walletlist=\think\Db::name('wallet')->where(['is_virtual'=>1,'is_currency'=>2])->select();
    return  $walletlist;
}

//生成钱包地址
function get_wetoken_url() {
    $res=uniqid().mt_rand(100000,999999);
    return '0x'.$res;
}

/**
 * 获取文件url
 */
function get_file_url($id = 0,$true=true)
{

    $info = Db::name('file')->where(['id' => $id])->field('path,url')->find();

    if (!empty($info['url'])) {
        return $info['url'];
        //return  $true?config('static_domain') . SYS_DS_PROS . $info['url']:DMOAIN_URL.config('static_domain') . SYS_DS_PROS . $info['url'];
    }

    if (!empty($info['path'])) {

        $root_url = get_file_root_path();
        return $true?$root_url . 'upload/file/'.$info['path']:DMOAIN_URL .'/'. 'upload/file/'.$info['path'];
    }

    return '暂无文件';
}

/**
 * 删除所有空目录
 * @param String $path 目录路径
 */
function rm_empty_dir($path)
{

    if (!(is_dir($path) && ($handle = opendir($path))!==false)) {

        return false;
    }

    while(($file = readdir($handle))!==false)
    {

        if (!($file != '.' && $file != '..')) {

            continue;
        }

        $curfile = $path . SYS_DS_PROS . $file;// 当前目录

        if (!is_dir($curfile)) {

            continue;
        }

        rm_empty_dir($curfile);

        if (count(scandir($curfile)) == 2) {

            rmdir($curfile);
        }
    }

    closedir($handle);
}


// +---------------------------------------------------------------------+
// | 时间相关函数
// +---------------------------------------------------------------------+

/**
 * 时间戳格式化
 * @param int $time
 * @return string 完整的时间显示
 */
function format_time($time = null, $format='Y-m-d H:i:s')
{

    if (null === $time) {

        $time = TIME_NOW;
    }

    return date($format, intval($time));
}

//发送短信
function send_sms($mobile, $content, $setting,$area=86)
{
    $setting=getConfig();
    if ($setting['sms_is_test'] == 1) {
        return null;
    }
    if ($setting['sms_is_open'] != 1) {
        return '短信功能暂未开启';
    }
    if (empty($setting['sms_user_name'])) {
        return '请先配置短信用户名';
    }
    if (empty($setting['sms_password'])) {
        return '请先配置短信密码';
    }
    if (empty($mobile)) {
        return '发送手机号码不能为空';
    }
    if (empty($content)) {
        return '发送内容不能为空';
    }
    $content.='【'.$setting['web_base_name'].'】';
    $statusStr = array(
        "0" => "短信发送成功",
        "-1" => "参数不全",
        "-2" => "服务器空间不支持,请确认支持curl或者fsocket，联系您的空间商解决或者更换空间！",
        "30" => "密码错误",
        "40" => "账号不存在",
        "41" => "余额不足",
        "42" => "帐户已过期",
        "43" => "IP地址限制",
        "50" => "内容含有敏感词"
    );
    if($area==86){

        $url='https://api.smsbao.com/sms?u='. $setting['sms_user_name'].'&p='.md5( $setting['sms_password']).'&m='.$mobile.'&c='. urlencode($content);
//        $url = 'http://service2.winic.org/service.asmx/SendInternationalMessages?uid=' . $setting['sms_user_name'] . '&pwd=' . $setting['sms_password'] . '&tos=' . $mobile . '&msg=' . urlencode($content).'&otime=""';
    }else{
        $mobile='+'.$area.$mobile;
        $url='https://api.smsbao.com/wsms?u='. $setting['sms_user_name'].'&p='.md5( $setting['sms_password']).'&m='.urlencode($mobile).'&c='. urlencode($content);
//        $url = 'http://service2.winic.org/service.asmx/SendMessages?uid=' . $setting['sms_user_name'] . '&pwd=' . $setting['sms_password'] . '&tos=' . $mobile . '&msg=' . urlencode($content).'&otime=""';
    }

//    $ch = curl_init();
//    curl_setopt($ch, CURLOPT_URL, $url);
//    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//    curl_setopt($ch, CURLOPT_POST, false);
//    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3000);
//    $handles = curl_exec($ch);
//    if (!preg_match('/\d{16}/',$handles)) {
//        return 0;
//    }else{
//        return 1;
//    }

//    $url1= 'http://api.smsbao.com/query?u='. $setting['sms_user_name'].'&p='.md5( $setting['sms_password']);
    $result =file_get_contents($url) ;
    if($result>0){
        return 0;
    }
    return 1;

}

/**
 * 获取指定日期段内每一天的日期
 * @param Date $startdate 开始日期
 * @param Date $enddate  结束日期
 * @return Array
 */
function get_date_from_range($startdate, $enddate)
{

    $stimestamp = strtotime($startdate);
    $etimestamp = strtotime($enddate);

    // 计算日期段内有多少天
    $days = ($etimestamp-$stimestamp)/86400+1;

    // 保存每天日期
    $date = [];

    for($i=0; $i<$days; $i++) {

        $date[] = date('Y-m-d', $stimestamp+(86400*$i));
    }

    return $date;
}

// +---------------------------------------------------------------------+
// | 调试函数
// +---------------------------------------------------------------------+

/**
 * 将数据保存为PHP文件，用于调试
 */
function sf($arr = [], $fpath = './test.php')
{

    $data = "<?php\nreturn ".var_export($arr, true).";\n?>";

    file_put_contents($fpath, $data);
}

/**
 * dump函数缩写
 */
function d($arr = [])
{
    dump($arr);
}

/**
 * dump与die组合函数缩写
 */
function dd($arr = [])
{
    dump($arr);die;
}


// +---------------------------------------------------------------------+
// | 其他函数
// +---------------------------------------------------------------------+

/**
 * 通过类创建逻辑闭包
 */
function create_closure($object = null, $method_name = '', $parameter = [])
{

    $func = function() use($object, $method_name, $parameter) {

        return call_user_func_array([$object, $method_name], $parameter);
    };

    return $func;
}

/**
 * 通过闭包控制缓存
 */
function auto_cache($key = '', $func = null, $time = 3)
{

    $result = cache($key);

    if (empty($result)) {

        $result = $func();

        !empty($result) && cache($key, $result, $time);
    }

    return $result;
}

/**
 * 通过闭包列表控制事务
 */
function closure_list_exe($list = [])
{

    Db::startTrans();

    try {

        foreach ($list as $closure) {

            $closure();
        }

        Db::commit();

        return true;
    } catch (\Exception $e) {

        Db::rollback();

        throw $e;
    }
}


//虚拟币 usdt价格
function coin_usdt($mid = 0,$symbol = ""){
    if(empty($mid)){
        $symbol = strtolower($symbol);
        $coin_usdt = \think\Cache::get($symbol."_coin_usdt");
        if(empty($coin_usdt)){
            $coin_usdt = Db::name("coin_usdt")->where("symbol",$symbol)->order("id desc")->value("usdt");
            \think\Cache::set($symbol."_coin_usdt",$coin_usdt,30);
        }
    }else{
        $coin_usdt = \think\Cache::get($mid."_coin_usdt");
        if(empty($coin_usdt)){
            $coin_usdt = Db::name("coin_usdt")->where("mid",$mid)->order("id desc")->value("usdt");
            \think\Cache::set($mid."_coin_usdt",$coin_usdt,30);
        }
    }

    return $coin_usdt;

}


//所有交易行情
function tickers(){
//  $result = Cache::get("kline_tickers");
    if(empty($result)){
        // $url = "https://data.gateio.co/api2/1/tickers";
        $url = "https://data.gateio.co/api2/1/marketlist";

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
        curl_setopt($ch, CURLOPT_BINARYTRANSFER, true) ; // 在启用 CURLOPT_RETURNTRANSFER 时候将获取数据返回
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);// 开启使用SSL
        $result = curl_exec($ch);

        curl_close($ch);
        if($result){
            \think\Cache::set("kline_tickers",$result,60);

            $end_id = Db::name("coin_usdt")->order("id desc")->find()['id'];
            dump($end_id);
            Db::name("coin_usdt")->where("id < ($end_id - 1000)")->delete();

            //将数字货币 价格 插入USDT价格表
            $res = json_decode($result,true);
            $datas = array();
            foreach($res['data'] as $key => $value){
                $data['add_time'] = time();
                $data['symbol'] = strtolower($value['symbol']);
                $data['usdt'] = $value['rate'];
                $data['name'] = $value['symbol'];
                $data['name_cn'] = $value['name_cn'];
                $data['name_en'] = $value['name_en'];
                $datas[] = $data;


            }
            Db::name("coin_usdt")->insertAll($datas);
        }
        $result =  \think\Cache::get("kline_tickers");
    }
    return $result = json_decode($result,true);
}


/****
 * 银行列表
 */
function get_bank(){
    $bank=[];
    if(!$bank){
        $str='{"CDB":"国家开发银行","ICBC":"中国工商银行","ABC":"中国农业银行","BOC":"中国银行","CCB":"中国建设银行","PSBC":"中国邮政储蓄银行","COMM":"交通银行","CMB":"招商银行","SPDB":"上海浦东发展银行","CIB":"兴业银行","HXBANK":"华夏银行","GDB":"广东发展银行","CMBC":"中国民生银行","CITIC":"中信银行","CEB":"中国光大银行","EGBANK":"恒丰银行","CZBANK":"浙商银行","BOHAIB":"渤海银行","SPABANK":"平安银行","SHRCB":"上海农村商业银行","YXCCB":"玉溪市商业银行","YDRCB":"尧都农商行","BJBANK":"北京银行","SHBANK":"上海银行","JSBANK":"江苏银行","HZCB":"杭州银行","NJCB":"南京银行","NBBANK":"宁波银行","HSBANK":"徽商银行","CSCB":"长沙银行","CDCB":"成都银行","CQBANK":"重庆银行","DLB":"大连银行","NCB":"南昌银行","FJHXBC":"福建海峡银行","HKB":"汉口银行","WZCB":"温州银行","QDCCB":"青岛银行","TZCB":"台州银行","JXBANK":"嘉兴银行","CSRCB":"常熟农村商业银行","NHB":"南海农村信用联社","CZRCB":"常州农村信用联社","H3CB":"内蒙古银行","SXCB":"绍兴银行","SDEB":"顺德农商银行","WJRCB":"吴江农商银行","ZBCB":"齐商银行","GYCB":"贵阳市商业银行","ZYCBANK":"遵义市商业银行","HZCCB":"湖州市商业银行","DAQINGB":"龙江银行","JINCHB":"晋城银行JCBANK","ZJTLCB":"浙江泰隆商业银行","GDRCC":"广东省农村信用社联合社","DRCBCL":"东莞农村商业银行","MTBANK":"浙江民泰商业银行","GCB":"广州银行","LYCB":"辽阳市商业银行","JSRCU":"江苏省农村信用联合社","LANGFB":"廊坊银行","CZCB":"浙江稠州商业银行","DYCB":"德阳商业银行","JZBANK":"晋中市商业银行","BOSZ":"苏州银行","GLBANK":"桂林银行","URMQCCB":"乌鲁木齐市商业银行","CDRCB":"成都农商银行","ZRCBANK":"张家港农村商业银行","BOD":"东莞银行","LSBANK":"莱商银行","BJRCB":"北京农村商业银行","TRCB":"天津农商银行","SRBANK":"上饶银行","FDB":"富滇银行","CRCBANK":"重庆农村商业银行","ASCB":"鞍山银行","NXBANK":"宁夏银行","BHB":"河北银行","HRXJB":"华融湘江银行","ZGCCB":"自贡市商业银行","YNRCC":"云南省农村信用社","JLBANK":"吉林银行","DYCCB":"东营市商业银行","KLB":"昆仑银行","ORBANK":"鄂尔多斯银行","XTB":"邢台银行","JSB":"晋商银行","TCCB":"天津银行","BOYK":"营口银行","JLRCU":"吉林农信","SDRCU":"山东农信","XABANK":"西安银行","HBRCU":"河北省农村信用社","NXRCU":"宁夏黄河农村商业银行","GZRCU":"贵州省农村信用社","FXCB":"阜新银行","HBHSBANK":"湖北银行黄石分行","ZJNX":"浙江省农村信用社联合社","XXBANK":"新乡银行","HBYCBANK":"湖北银行宜昌分行","LSCCB":"乐山市商业银行","TCRCB":"江苏太仓农村商业银行","BZMD":"驻马店银行","GZB":"赣州银行","WRCB":"无锡农村商业银行","BGB":"广西北部湾银行","GRCB":"广州农商银行","JRCB":"江苏江阴农村商业银行","BOP":"平顶山银行","TACCB":"泰安市商业银行","CGNB":"南充市商业银行","CCQTGB":"重庆三峡银行","XLBANK":"中山小榄村镇银行","HDBANK":"邯郸银行","KORLABANK":"库尔勒市商业银行","BOJZ":"锦州银行","QLBANK":"齐鲁银行","BOQH":"青海银行","YQCCB":"阳泉银行","SJBANK":"盛京银行","FSCB":"抚顺银行","ZZBANK":"郑州银行","SRCB":"深圳农村商业银行","BANKWF":"潍坊银行","JJBANK":"九江银行","JXRCU":"江西省农村信用","HNRCU":"河南省农村信用","GSRCU":"甘肃省农村信用","SCRCU":"四川省农村信用","GXRCU":"广西省农村信用","SXRCCU":"陕西信合","WHRCB":"武汉农村商业银行","YBCCB":"宜宾市商业银行","KSRB":"昆山农村商业银行","SZSBK":"石嘴山银行","HSBK":"衡水银行","XYBANK":"信阳银行","NBYZ":"鄞州银行","ZJKCCB":"张家口市商业银行","XCYH":"许昌银行","JNBANK":"济宁银行","CBKF":"开封市商业银行","WHCCB":"威海市商业银行","HBC":"湖北银行","BOCD":"承德银行","BODD":"丹东银行","JHBANK":"金华银行","BOCY":"朝阳银行","LSBC":"临商银行","BSB":"包商银行","LZYH":"兰州银行","BOZK":"周口银行","DZBANK":"德州银行","SCCB":"三门峡银行","AYCB":"安阳银行","ARCU":"安徽省农村信用社","HURCB":"湖北省农村信用社","HNRCC":"湖南省农村信用社","NYNB":"广东南粤银行","LYBANK":"洛阳银行","NHQS":"农信银清算中心","CBBQS":"城市商业银行资金清算中心"}';
        $arr=json_decode($str,true);
        $arr=array_values($arr);
        cache('bank',$arr);
        $bank=$arr;
    }

    return $bank;

}

/****
 * 银行列表
 */
function get_bank1(){
    $bank=[];
    if(!$bank){
        $str='{"CDB":"国家开发银行","ICBC":"中国工商银行","ABC":"中国农业银行","BOC":"中国银行","CCB":"中国建设银行","PSBC":"中国邮政储蓄银行","COMM":"交通银行","CMB":"招商银行","SPDB":"上海浦东发展银行","CIB":"兴业银行","HXBANK":"华夏银行","GDB":"广东发展银行","CMBC":"中国民生银行","CITIC":"中信银行","CEB":"中国光大银行","EGBANK":"恒丰银行","CZBANK":"浙商银行","BOHAIB":"渤海银行","SPABANK":"平安银行","SHRCB":"上海农村商业银行","YXCCB":"玉溪市商业银行","YDRCB":"尧都农商行","BJBANK":"北京银行","SHBANK":"上海银行","JSBANK":"江苏银行","HZCB":"杭州银行","NJCB":"南京银行","NBBANK":"宁波银行","HSBANK":"徽商银行","CSCB":"长沙银行","CDCB":"成都银行","CQBANK":"重庆银行","DLB":"大连银行","NCB":"南昌银行","FJHXBC":"福建海峡银行","HKB":"汉口银行","WZCB":"温州银行","QDCCB":"青岛银行","TZCB":"台州银行","JXBANK":"嘉兴银行","CSRCB":"常熟农村商业银行","NHB":"南海农村信用联社","CZRCB":"常州农村信用联社","H3CB":"内蒙古银行","SXCB":"绍兴银行","SDEB":"顺德农商银行","WJRCB":"吴江农商银行","ZBCB":"齐商银行","GYCB":"贵阳市商业银行","ZYCBANK":"遵义市商业银行","HZCCB":"湖州市商业银行","DAQINGB":"龙江银行","JINCHB":"晋城银行JCBANK","ZJTLCB":"浙江泰隆商业银行","GDRCC":"广东省农村信用社联合社","DRCBCL":"东莞农村商业银行","MTBANK":"浙江民泰商业银行","GCB":"广州银行","LYCB":"辽阳市商业银行","JSRCU":"江苏省农村信用联合社","LANGFB":"廊坊银行","CZCB":"浙江稠州商业银行","DYCB":"德阳商业银行","JZBANK":"晋中市商业银行","BOSZ":"苏州银行","GLBANK":"桂林银行","URMQCCB":"乌鲁木齐市商业银行","CDRCB":"成都农商银行","ZRCBANK":"张家港农村商业银行","BOD":"东莞银行","LSBANK":"莱商银行","BJRCB":"北京农村商业银行","TRCB":"天津农商银行","SRBANK":"上饶银行","FDB":"富滇银行","CRCBANK":"重庆农村商业银行","ASCB":"鞍山银行","NXBANK":"宁夏银行","BHB":"河北银行","HRXJB":"华融湘江银行","ZGCCB":"自贡市商业银行","YNRCC":"云南省农村信用社","JLBANK":"吉林银行","DYCCB":"东营市商业银行","KLB":"昆仑银行","ORBANK":"鄂尔多斯银行","XTB":"邢台银行","JSB":"晋商银行","TCCB":"天津银行","BOYK":"营口银行","JLRCU":"吉林农信","SDRCU":"山东农信","XABANK":"西安银行","HBRCU":"河北省农村信用社","NXRCU":"宁夏黄河农村商业银行","GZRCU":"贵州省农村信用社","FXCB":"阜新银行","HBHSBANK":"湖北银行黄石分行","ZJNX":"浙江省农村信用社联合社","XXBANK":"新乡银行","HBYCBANK":"湖北银行宜昌分行","LSCCB":"乐山市商业银行","TCRCB":"江苏太仓农村商业银行","BZMD":"驻马店银行","GZB":"赣州银行","WRCB":"无锡农村商业银行","BGB":"广西北部湾银行","GRCB":"广州农商银行","JRCB":"江苏江阴农村商业银行","BOP":"平顶山银行","TACCB":"泰安市商业银行","CGNB":"南充市商业银行","CCQTGB":"重庆三峡银行","XLBANK":"中山小榄村镇银行","HDBANK":"邯郸银行","KORLABANK":"库尔勒市商业银行","BOJZ":"锦州银行","QLBANK":"齐鲁银行","BOQH":"青海银行","YQCCB":"阳泉银行","SJBANK":"盛京银行","FSCB":"抚顺银行","ZZBANK":"郑州银行","SRCB":"深圳农村商业银行","BANKWF":"潍坊银行","JJBANK":"九江银行","JXRCU":"江西省农村信用","HNRCU":"河南省农村信用","GSRCU":"甘肃省农村信用","SCRCU":"四川省农村信用","GXRCU":"广西省农村信用","SXRCCU":"陕西信合","WHRCB":"武汉农村商业银行","YBCCB":"宜宾市商业银行","KSRB":"昆山农村商业银行","SZSBK":"石嘴山银行","HSBK":"衡水银行","XYBANK":"信阳银行","NBYZ":"鄞州银行","ZJKCCB":"张家口市商业银行","XCYH":"许昌银行","JNBANK":"济宁银行","CBKF":"开封市商业银行","WHCCB":"威海市商业银行","HBC":"湖北银行","BOCD":"承德银行","BODD":"丹东银行","JHBANK":"金华银行","BOCY":"朝阳银行","LSBC":"临商银行","BSB":"包商银行","LZYH":"兰州银行","BOZK":"周口银行","DZBANK":"德州银行","SCCB":"三门峡银行","AYCB":"安阳银行","ARCU":"安徽省农村信用社","HURCB":"湖北省农村信用社","HNRCC":"湖南省农村信用社","NYNB":"广东南粤银行","LYBANK":"洛阳银行","NHQS":"农信银清算中心","CBBQS":"城市商业银行资金清算中心"}';
        $arr=json_decode($str,true);
//        $arr=array_values($arr);
//        cache('bank',$arr);
        $bank=$arr;
    }

    return $bank;

}

/****
 * 银行列表
 */
function get_bank_log($key){

    return 'https://apimg.alipay.com/combo.png?d=cashier&t='.$key;


}


//采集数字货币订单
function coin_collect_order($symbol,$address,$mid){
    if(empty($symbol) || empty($address) || empty($mid)){
        return [];
    }
    $money = Db::name("wallet")->where(["id"=>$mid])->find();
    if(empty($money)){
        return [];
    }
    $host = $money['rpc_host'];
    $list = array();
    if(strtolower($symbol) == "eth"){
        //ETH 订单采集
        $url = "https://api.etherscan.io/api?module=account&action=txlist&address=".$address."&startblock=0&endblock=99999999&page=1&offset=20&sort=desc&apikey=YourApiKeyToken";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
        curl_setopt($ch, CURLOPT_BINARYTRANSFER, true) ; // 在启用 CURLOPT_RETURNTRANSFER 时候将获取数据返回
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);// 开启使用SSL
        $result = curl_exec($ch);
        curl_close($ch);
        if(!empty($result)){
            $result = json_decode($result,true);
            if(isset($result['status']) && $result['status'] == 1){
                foreach($result['result'] as $value){
                    $data['tx'] = $value['hash'];
                    $data['from'] = $value['from'];
                    $data['to'] = $value['to'];
                    $data['number'] = $value['value']/1000000000000000000;
                    $data['txFee'] = $value['gas']/1000000000000000000;
                    $data['money'] =  $data['number']*Db::name('wallet')->where(['symbol'=>$symbol])->value('parities');
                    if($data['to'] == $address && $data['number'] >= 0.01){
                        //充值订单
                        $list[] = $data;
                    }
                }
            }
        }
    }elseif(strtolower($symbol) == "ccie" || strtolower($symbol) == "usdt"){
        //ETH 代币
        $contractaddress = $money['contractaddress'];
        $url = "https://api.etherscan.io/api?module=account&action=tokentx&contractaddress=".$contractaddress."&address=".$address."&page=1&offset=20&sort=desc&apikey=YourApiKeyToken";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
        curl_setopt($ch, CURLOPT_BINARYTRANSFER, true) ; // 在启用 CURLOPT_RETURNTRANSFER 时候将获取数据返回
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);// 开启使用SSL
        $result = curl_exec($ch);
        curl_close($ch);

        if(!empty($result)){
            $result = json_decode($result,true);
            if(isset($result['status']) && $result['status'] == 1){
                $point = 1000000000000000000;
                if(strtolower($symbol) == "ccie"){
                    $point = 100000000;
                }elseif(strtolower($symbol) == "usdt"){
                	$point = 1000000;
                }
                foreach($result['result'] as $value){
                    $data['tx'] = $value['hash'];
                    $data['from'] = $value['from'];
                    $data['to'] = $value['to'];
                    $data['number'] = $value['value']/$point;
                    $data['txFee'] = $value['gas']/1000000000000000000;
                    $data['money'] =  $data['number']*Db::name('wallet')->where(['symbol'=>$symbol])->value('parities');
                    if($data['to'] == $address && $data['number'] >= 0.01){
                        //充值订单
                        $list[] = $data;
                    }
                }
            }
        }
    }elseif(strtolower($symbol) == "usdt"){
        //USDT
        $res = "https://api.omniexplorer.info/v1/transaction/address";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$res);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
        curl_setopt($ch, CURLOPT_BINARYTRANSFER, true) ; // 在启用 CURLOPT_RETURNTRANSFER 时候将获取数据返回
        curl_setopt($ch, CURLOPT_POST, 1);
        $post_data = array(
            "addr" => $address
        );
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);// 开启使用SSL
        $result = curl_exec($ch);
        curl_close($ch);
        if(!empty($result)){
            $result = json_decode($result,true);
            if(!empty($result['transactions'])){
                foreach($result['transactions'] as $value){
                    $data['tx'] = $value['txid'];
                    $data['from'] = $value['sendingaddress'];
                    $data['to'] = $value['referenceaddress'];
                    $data['number'] = $value['amount'];
                    $data['money'] = $value['amount']*Db::name('wallet')->where(['symbol'=>$symbol])->value('parities');
                    if($data['to'] == $address && $data['number'] >= 0.01){
                        //充值订单
                        $list[] = $data;
                    }
                }
            }
        }
    }elseif(strtolower($symbol) == "btc"){
        //USDT
        $res = $host."/index/usdt/listtransactions?address=".$address;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$res);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
        curl_setopt($ch, CURLOPT_BINARYTRANSFER, true) ; // 在启用 CURLOPT_RETURNTRANSFER 时候将获取数据返回
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);// 开启使用SSL
        $result = curl_exec($ch);
        curl_close($ch);
        if(!empty($result)){
            $result = json_decode($result,true);
            if(!empty($result)){
                foreach($result as $value){
                    $data['tx'] = $value['txid'];
                    $data['from'] = empty($value['sendingaddress'])?"":$value['sendingaddress'];
                    $data['to'] = empty($value['sendingaddress'])?"":$value['sendingaddress'];
                    $data['number'] = $value['amount'];
                    $data['money'] = $value['amount']*Db::name('wallet')->where(['symbol'=>$symbol])->value('parities');
                    if($value['category'] == "receive" && $data['number'] >= 0.01){
                        //充值订单
                        $data['to'] = $address;
                        $list[] = $data;
                    }
                }
            }
        }
    }
    return $list;
}

//虚拟币交易号 查询订单状态是否交易成功
function query_tx_status($symbol,$tx,$mid){
    if(empty($tx) || empty($symbol)){
        return 0;
    }
    if(strtolower($symbol) == "eth" || strtolower($symbol) == "ccie" || strtolower($symbol) == "usdt"){
        //以太坊
        $url = "https://api.etherscan.io/api?module=transaction&action=gettxreceiptstatus&txhash=".$tx."&apikey=UGUIQSU9MKF9TE643P9JNF63XTJPD94Z8X";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
        curl_setopt($ch, CURLOPT_BINARYTRANSFER, true) ; // 在启用 CURLOPT_RETURNTRANSFER 时候将获取数据返回
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);// 开启使用SSL
        $result = curl_exec($ch);
        curl_close($ch);
        $result = json_decode($result,true);
        if(isset($result['result']['status'])){
            if($result['result']['status'] == 1){
                return 1;
            }else{
                return 0;
            }
        }else{
            return 0;
        }
    }elseif(strtolower($symbol) == "etc"){
        //ETC 以太坊经典
        return 0;
    }elseif(strtolower($symbol) == "usdt" || strtolower($symbol) == "btc"){
        $money = Db::name("finance_money")->where(["id"=>$mid])->find();
        $host = $money['ip'];
        $password = $money['password'];
        $url = $host."/index/usdt/trade_order_status";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
        curl_setopt($ch, CURLOPT_BINARYTRANSFER, true) ; // 在启用 CURLOPT_RETURNTRANSFER 时候将获取数据返回
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);// 开启使用SSL
        curl_setopt($ch, CURLOPT_POST, 1);
        $post_data = array(
            "txid" => $tx,
            "symbol" => $symbol
        );
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        $result = curl_exec($ch);
        curl_close($ch);
        if(!empty($result)){
            if($result == 1){
                return 1;
            }else{
                return 0;
            }
        }else{
            return 0;
        }

    }



}



/**

 * 批量更新方法 返回sql语句

 * @param $table   varchar 表名

 * @param $knum    varchar 数组首下标的key

 * @param $arrUser array   数组

 */

function updateAllSql($table,$knum,$arrUser,$name = "userid"){
    //批量更新到账户表

    $arrUser_keys = array_keys($arrUser);

    //拼接批量更新sql语句

    $sql = "UPDATE $table SET ";

    //合成sql语句
    foreach ($arrUser[$knum] as $key => $value){

        $sql .= "{$key} = CASE ".$name." ";

        foreach ($arrUser as $arrUser_key => $arrUser_value) {

            $sql .= sprintf("WHEN %d THEN {$key}+ %s ", $arrUser_key, $arrUser_value[$key]);

        }

        $sql .= "END, ";

    }

    //把最后一个,去掉

    $sql = substr($sql, 0, strrpos($sql, ','));

    //合并所有id

    $ids = implode(',', $arrUser_keys);

    //拼接sql

    $sql .= " WHERE ".$name." IN ({$ids})";

    return $sql;

}


function getTodayStart(){
    $date=date('Y-m-d');
    $time1=strtotime($date.' 00:00:00');
    return $time1;
}


function getTodayEnd(){
    $date=date('Y-m-d');
    $time1=strtotime($date.' 23:59:59');
    return $time1;
}

function time_to_seconds($time_string){
    $hour = intval(explode(':',$time_string)[0]);
    $minute = intval(explode(':',$time_string)[1]);
    $seconds = $hour*60*60+$minute*60;
    return $seconds;
}


//七牛base64上传方法
function phpCurlImg($remote_server,$post_string,$upToken)
{
    $headers = array();
    $headers[] = 'Content-Type:application/octet-stream';
    $headers[] = 'Authorization:UpToken ' . $upToken;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $remote_server);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    $data = curl_exec($ch);
    curl_close($ch);
    return $data;
}
/**
 * @param $str
 * @return mixed
 */
function format_money($num,$number=2){
    return sprintf("%.".$number."f",$num);
}


//获取ip信息
function get_ip_info($post_string,$name='')
{
//    $remote_server='http://ip.taobao.com/service/getIpInfo.php?ip='.$post_string;
    $remote_server='https://open.onebox.so.com/dataApi?type=ip&src=onebox&query=ip&ip='.$post_string.'&url=ip';
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,$remote_server);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
    curl_setopt($ch, CURLOPT_BINARYTRANSFER, true) ; // 在启用 CURLOPT_RETURNTRANSFER 时候将获取数据返回
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);// 开启使用SSL
    curl_setopt($ch, CURLOPT_POST, 1);
    $data = curl_exec($ch);
    curl_close($ch);
    $data=json_decode($data,true);
    if($data){
        $arr=[];
        foreach ($data as $k=>$v){
            switch ($k){
                case 0:
                    $arr['country']=$v;
                    break;
                case 1:
                    $arr['region']=$v;
                    break;
                case 2:
                    $arr['city']=$v;
                    break;
                case 5:
                    $arr['isp']=$v;
                    break;


            }
        }
        empty($arr['country']) && $arr['country']='中国';
        empty($arr['region']) && $arr['region']='';
        empty($arr['city']) && $arr['city']='';
        empty($arr['isp']) && $arr['isp']='';
        if($name){
            return $arr[$name];
        }else{
            return $arr;
        }
    }
    return false ;
}


//身份证实名验证接口

function check_card($idcard,$true_name){
    $host = "https://naidcard.market.alicloudapi.com";
    $path = "/nidCard";
    $method = "GET";
    $appcode = getConfig('idcard_appcode');
    $headers = array();
    array_push($headers, "Authorization:APPCODE " . $appcode);
    $querys = "idCard=".$idcard."&name=".$true_name;
    $bodys = "";
    $url = $host . $path . "?" . $querys;

    $curl = curl_init();
    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($curl, CURLOPT_FAILONERROR, false);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_HEADER, false);
   // curl_setopt($curl, CURLOPT_HEADER, true);   //如不输出json, 请打开这行代码，打印调试头部状态码。
    //状态码: 200 正常；400 URL无效；401 appCode错误； 403 次数用完； 500 API网管错误
    if (1 == strpos("$".$host, "https://"))
    {
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    }
    $out_put = curl_exec($curl);
    if($out_put){
        return json_decode($out_put,true);
    }else{
        return false;
    }

}
function getConfig($key=''){
    if(!cache('sms_config')){
        cache('sms_config',\app\common\model\SysConfig::where('1=1')->column('code,value'));
    }

    if($key){
        $a=cache('sms_config');
        if(empty( $a[$key])){
            $a=\app\common\model\SysConfig::where('1=1')->column('code,value');
            cache('sms_config',$a);
        }
        return $a[$key];
    }

    return   cache('sms_config');

}

 function checkName($name)
{
    $ret = true;
    if (!preg_match('/^[\x{4e00}-\x{9fa5}]+[·•]?[\x{4e00}-\x{9fa5}]+$/u', $name)) {
        return false;
    }
    $strLen = mb_strlen($name);
    if ($strLen < 2 || $strLen > 8) {//字符长度2到8之间
        return false;
    }

    return $ret;
}


// 转化html标签
function html_change($str){
    return  htmlspecialchars_decode(html_entity_decode($str));
}



//验证身份证
function is_idcard( $id )
{
    $id = strtoupper($id);
    $regx = "/(^\d{15}$)|(^\d{17}([0-9]|X)$)/";
    $arr_split = array();
    if (!preg_match($regx, $id)) {
        return FALSE;
    }
    if (15 == strlen($id)) //检查15位
    {
        $regx = "/^(\d{6})+(\d{2})+(\d{2})+(\d{2})+(\d{3})$/";

        @preg_match($regx, $id, $arr_split);
        //检查生日日期是否正确
        $dtm_birth = "19" . $arr_split[2] . '/' . $arr_split[3] . '/' . $arr_split[4];
        if (!strtotime($dtm_birth)) {
            return FALSE;
        } else {
            return TRUE;
        }
    } else      //检查18位
    {
        $regx = "/^(\d{6})+(\d{4})+(\d{2})+(\d{2})+(\d{3})([0-9]|X)$/";
        @preg_match($regx, $id, $arr_split);
        $dtm_birth = $arr_split[2] . '/' . $arr_split[3] . '/' . $arr_split[4];
        if (!strtotime($dtm_birth)) //检查生日日期是否正确
        {
            return FALSE;
        } else {
            //检验18位身份证的校验码是否正确。
            //校验位按照ISO 7064:1983.MOD 11-2的规定生成，X可以认为是数字10。
            $arr_int = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
            $arr_ch = array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
            $sign = 0;
            for ($i = 0; $i < 17; $i++) {
                $b = (int)$id{$i};
                $w = $arr_int[$i];
                $sign += $b * $w;
            }
            $n = $sign % 11;
            $val_num = $arr_ch[$n];
            if ($val_num != substr($id, 17, 1)) {
                return false;
            } //phpfensi.com
            else {
                return true;
            }
        }
    }
}

////获取汇率换算接口
//function convertCurrency($from, $to, $amount){
//    $time=getMillisecond();
//    $data = file_get_contents("https://api.jijinhao.com/plus/convert.htm?from_tkc=".$from."&to_tkc=".$to."&amount=".$amount."&_=".$time);
//    $arr=explode("'",$data);
//    return format_money($arr[1], 4);
//
//}

//获取汇率换算接口
function convertCurrency($from, $to, $amount){
    ini_set('user_agent','Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)');
    $data = file_get_contents("http://huilv.911cha.com/".$from.$to.".html");
    preg_match_all('|<p>(.+?)<\/p>|i',$data,$array);
    if($array){
        if(preg_match('/(\d+)\.(\d+)/is',$array[1][0],$arr)){

            return $arr[0];

        }

    }else{
        return false;
    }


}
function geturldata($url)
{
    $ch = curl_init();
    curl_setopt ($ch, CURLOPT_URL, $url);
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT,10);
    $content = curl_exec($ch);
    return $content;
}
//获取毫秒
 function getMillisecond(){
    list($msec, $sec) = explode(' ', microtime());
    $msectime =  (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
    return $msectimes = substr($msectime,0,13);
}


//返回手机号信息
function get_phone_info($mobile){
    $url = "https://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=".$mobile;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,$url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_BINARYTRANSFER, true); // 在启用 CURLOPT_RETURNTRANSFER 时候将获取数据返回
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);// 开启使用SSL
    $res = curl_exec($ch);
    curl_close($ch);

    $res = trim(explode('=',$res)[1]);
//    d($res);
    $res = json_decode($res, true);
    if(is_array($res)){
        return false;
    }else{
        return true;
    }
}

//获取OTC订单
function getPrice(){
    $arr=[];
    $max_money=getConfig('otc_max_money');
    $len=ceil($max_money/200);
    for ($i=1;$i<=$len;$i++){
        $moeny=200*$i;
        if($moeny<=$max_money){
            $arr[]=$moeny;
        }

    }
    return $arr;

}

/**
 * 发送用户消息
 */
function user_notice($uid,$title='',$type=1,$content=''){
    if(!$content){
        $content=$title;
    }
    \app\common\model\UserNotice::create([
        'title'=>$title,
        'user_id'=>$uid,
        'content'=>$content,
        'type'=>$type
    ]);
}


//型号

function mobile_type()
{
    $user_agent = $_SERVER['HTTP_USER_AGENT'];
    if (stripos($user_agent, "iPhone") !== false) {
        $brand = 'iPhone';
    } else if (stripos($user_agent, "SAMSUNG") !== false || stripos($user_agent, "Galaxy") !== false || strpos($user_agent, "GT-") !== false || strpos($user_agent, "SCH-") !== false || strpos($user_agent, "SM-") !== false) {
        $brand = '三星';
    } else if (stripos($user_agent, "Huawei") !== false || stripos($user_agent, "Honor") !== false || stripos($user_agent, "H60-") !== false || stripos($user_agent, "H30-") !== false) {
        $brand = '华为';
    } else if (stripos($user_agent, "Lenovo") !== false) {
        $brand = '联想';
    } else if (strpos($user_agent, "MI-ONE") !== false || strpos($user_agent, "MI 1S") !== false || strpos($user_agent, "MI 2") !== false || strpos($user_agent, "MI 3") !== false || strpos($user_agent, "MI 4") !== false || strpos($user_agent, "MI-4") !== false) {
        $brand = '小米';
    } else if (strpos($user_agent, "HM NOTE") !== false || strpos($user_agent, "HM201") !== false) {
        $brand = '红米';
    } else if (stripos($user_agent, "Coolpad") !== false || strpos($user_agent, "8190Q") !== false || strpos($user_agent, "5910") !== false) {
        $brand = '酷派';
    } else if (stripos($user_agent, "ZTE") !== false || stripos($user_agent, "X9180") !== false || stripos($user_agent, "N9180") !== false || stripos($user_agent, "U9180") !== false) {
        $brand = '中兴';
    } else if (stripos($user_agent, "OPPO") !== false || strpos($user_agent, "X9007") !== false || strpos($user_agent, "X907") !== false || strpos($user_agent, "X909") !== false || strpos($user_agent, "R831S") !== false || strpos($user_agent, "R827T") !== false || strpos($user_agent, "R821T") !== false || strpos($user_agent, "R811") !== false || strpos($user_agent, "R2017") !== false) {
        $brand = 'OPPO';
    } else if (strpos($user_agent, "HTC") !== false || stripos($user_agent, "Desire") !== false) {
        $brand = 'HTC';
    } else if (stripos($user_agent, "vivo") !== false) {
        $brand = 'vivo';
    } else if (stripos($user_agent, "K-Touch") !== false) {
        $brand = '天语';
    } else if (stripos($user_agent, "Nubia") !== false || stripos($user_agent, "NX50") !== false || stripos($user_agent, "NX40") !== false) {
        $brand = '努比亚';
    } else if (strpos($user_agent, "M045") !== false || strpos($user_agent, "M032") !== false || strpos($user_agent, "M355") !== false) {
        $brand = '魅族';
    } else if (stripos($user_agent, "DOOV") !== false) {
        $brand = '朵唯';
    } else if (stripos($user_agent, "GFIVE") !== false) {
        $brand = '基伍';
    } else if (stripos($user_agent, "Gionee") !== false || strpos($user_agent, "GN") !== false) {
        $brand = '金立';
    } else if (stripos($user_agent, "HS-U") !== false || stripos($user_agent, "HS-E") !== false) {
        $brand = '海信';
    } else if (stripos($user_agent, "Nokia") !== false) {
        $brand = '诺基亚';
    } else {
        $brand = '其他手机';
    }
    return $brand;

}

function arrangement_total($money){
    if($money>100000000){
        return format_money($money/100000000,2).'億';
    }elseif($money>10000000){
        return format_money($money/10000000,2).'千萬';
    }elseif($money>1000000){
        return format_money($money/1000000,2).'百萬';
    }elseif($money>100000){
        return format_money($money/100000,2).'十萬';
    }elseif($money>10000){
        return format_money($money/10000,2).'萬';
    }
    return $money;


}

function filter_money($money,$accuracy=2)
{
    $str_ret = 0;
    if (empty($money) === false) {
        $str_ret = sprintf("%.".$accuracy."f", substr(sprintf("%.".($accuracy+1)."f", floatval($money)), 0, -1));
    }

    return floatval($str_ret);
}

function send_submall($email,$data){
    $server='https://api.mysubmail.com/';
    $mail_configs['appid']=getConfig('email_app_id');
    $mail_configs['appkey']=getConfig('email_app_key');
    $mail_configs['sign_type']='normal';
    $mail_configs['server']=$server;
    include_once(ROOT_PATH . 'extend/submall/SUBMAILAutoload.php');
    $submail=new MAILXsend($mail_configs);
    $submail->AddTo($email);
    $submail->SetSender(getConfig('email_app_pay'),getConfig('email_username'));
    $submail->SetSubject(getConfig('email_title'));
    $submail->SetProject(getConfig('email_template_id'));
    $submail->AddLink('link','https://download.ccieclub.co/reg/index.html');
    foreach ($data as $k=>$v){
        $submail->AddVar($k,$v);
    }
    $submail->AddHeaders('X-Accept','zh-cn');
    $submail->AddHeaders('X-Mailer','my App');
    $submail->setAsynchronous(false);
    $xsend=$submail->xsend();
    return $xsend;
    /*
     |打印服务器返回值
     |--------------------------------------------------------------------------
     */

}
function send_notice_submall($email,$data){
    $server='https://api.mysubmail.com/';
    $mail_configs['appid']=getConfig('email_app_id');
    $mail_configs['appkey']=getConfig('email_app_key');
    $mail_configs['sign_type']='normal';
    $mail_configs['server']=$server;
    include_once(ROOT_PATH . 'extend/submall/SUBMAILAutoload.php');
    $submail=new MAILXsend($mail_configs);
    $submail->AddTo($email);
    $submail->SetSender(getConfig('email_app_pay'),getConfig('email_username'));
    $submail->SetSubject(getConfig('email_title'));
    $submail->SetProject('GfLh22');
    $submail->AddLink('link','https://download.ccieclub.co/reg/index.html');
    foreach ($data as $k=>$v){
        $submail->AddVar($k,$v);
    }
    $submail->AddHeaders('X-Accept','zh-cn');
    $submail->AddHeaders('X-Mailer','my App');
    $submail->setAsynchronous(false);
    $xsend=$submail->xsend();
    return $xsend;

    /*
     |打印服务器返回值
     |--------------------------------------------------------------------------
     */

}

